package org.jl.demo.authority.controller.group;

import jakarta.annotation.Resource;
import org.jl.demo.authority.model.po.Group;
import org.jl.demo.authority.service.GroupService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/group")
public class GroupController {

    @Resource
    private GroupService groupService;

    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "5") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Group> groups = groupService.page(pageable);
        model.addAttribute("groups", groups);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", groups.getTotalPages());
        return "/group/index";
    }

    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("group", new Group());
        return "/group/add";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute Group group) {
        groupService.insert(group);
        return "redirect:/group/";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Integer id, Model model, @RequestParam(defaultValue = "0") int page) {
        model.addAttribute("group", groupService.getById(id).orElse(new Group()));
        model.addAttribute("currentPage", page);
        return "/group/edit";
    }

    @PostMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, @ModelAttribute Group groupDetail, @RequestParam(defaultValue = "0") int page) {
        groupService.update(id, groupDetail);
        return "redirect:/group/?page=" + page;
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        groupService.delete(id);
        return "redirect:/group/";
    }
}